package nettyProtocol.handshakeAndAuthentication;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import nettyProtocol.pojo.Header;
import nettyProtocol.pojo.NettyMessage;


public class LoginAuthReqHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //三次握手成功，客户端构建，握手请求消息给服务端
        NettyMessage message = buildLoginReq();
        ctx.writeAndFlush(message);
        System.out.println("客户端发送握手请求：" + message);
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        NettyMessage message = (NettyMessage) msg;

        //如果是握手消息，需要判断是否认证成功
        if(message.getHeader()!= null && message.getHeader().getType() == MessageType.LOGIN_REQ.value){
            if (message.getBody() != null)
            {
                String loginResult = message.getBody().toString();
                if (loginResult.equals("login_ok"))
                {
                    System.out.println("Login is success :" + message);
                    // 透传给后面的Handler处理
                    ctx.fireChannelRead(msg);
                }
                else
                {
                    // 握手失败，关闭连接
                    ctx.close();
                    System.out.println("握手失败，关闭连接");
                }
            }
            else
            {
                // 握手失败，关闭连接
                ctx.close();
                System.out.println("握手失败，关闭连接");
            }
        } else {
//            System.out.println("收到回复，开始传给下一条链路");
            ctx.fireChannelRead(msg);
        }
    }
    private NettyMessage buildLoginReq() {
        NettyMessage message = new NettyMessage();
        Header header = new Header();
        header.setType(MessageType.LOGIN_REQ.value);
        message.setHeader(header);
        return message;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("LoginAuthReqHandler");
        ctx.close();
        ctx.fireExceptionCaught(cause);
    }


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception
    {
        ctx.flush();
    }
}
